<template>
  <div class="community-container">
    <!-- 分类导航栏 + 写文章按钮 -->
    <div class="category-bar">
      <div class="tabs">
        <span
          v-for="tab in tabs"
          :key="tab"
          :class="{ active: activeTab === tab }"
          @click="activeTab = tab"
        >
          {{ tab }}
        </span>
      </div>
      <button class="write-article-btn" @click="goWriteArticle"
              style="margin-right: 120px; display: inline-flex; align-items: center; gap: 6px;">
        <img src="../../../assets/img/mysvg/publish.svg" alt="笔图标"
             style="width: 1em; height: 1em; filter: brightness(0) invert(1); vertical-align: middle;"/>
        <span style="display: inline-block;margin-bottom: 3px;">发布文章</span>
      </button>

    </div>

    <div class="main-layout">
      <!-- 左侧内容区 - 固定宽度 -->
      <div class="left-panel" style="width: 850px; flex: none;">
        <!-- 热门标签 -->
        <div class="tag-bar">
          <span class="tag" v-for="tag in tags" :key="tag"># {{ tag }}</span>
        </div>

        <!-- 文章列表 -->
        <div v-for="(post, index) in articles" :key="index" class="article-item">
          <div class="article-content-area">
            <div class="article-left">
              <h3 class="article-title" @click="goDetail(post.articleId)">{{ post.title }}</h3>
              <div class="article-content">{{ post.content }}</div>

              <div class="article-meta">
                <span><i class="el-icon-view"></i> {{ post.views }}</span>
                <span><i class="el-icon-chat-dot-square"></i> {{ post.comments }}</span>
                <span><i class="el-icon-thumb"></i> {{ post.likes }}</span>
              </div>
            </div>
            <div class="article-cover">
              <img :src="post.cover" alt="封面图"/>
              <div class="cover-meta">
                <span class="author">{{ post.author }}</span>
                <span class="time">&nbsp;&nbsp;{{ post.time }}</span>
              </div>
            </div>
          </div>
        </div>

        <!-- 加载更多 -->
        <div class="load-more-container">
          <span
            v-if="!noMore && !loading"
            class="load-more-text"
            @click="fetchArticles"
            style="text-decoration: none;"
          >
            加载更多
          </span>
          <div v-if="loading" class="loading-text">加载中...</div>
          <div v-if="noMore" class="no-more-text">已加载全部内容</div>
        </div>
      </div>

      <!-- 右侧推荐 -->
      <div class="right-panel" style="position: absolute; right: 20px; width: 320px;margin-top: 70px;">
        <div class="card">
          <div class="card-title">推荐作者</div>
          <ul class="author-list">
            <li v-for="a in recommendedAuthors" :key="a.name">
              <div class="author-name">{{ a.name }}</div>
              <div class="author-desc">{{ a.desc }}</div>
            </li>
          </ul>
        </div>

        <div class="card">
          <div class="card-title">热门话题</div>
          <div class="hot-topics">
            <span class="tag" v-for="tag in hotTopics" :key="tag"># {{ tag }}</span>
          </div>
        </div>

        <div class="card">
          <div class="card-title">广告位</div>
          <img src="https://picsum.photos/250/100?grayscale" class="ad-img"/>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import ArticleApi from "~/api/article";
import article from "~/api/article";

export default {
  name: "CommunityPage",
  computed: {
    article() {
      return article
    }
  },
  data() {
    return {
      activeTab: "文章",
      tabs: ["文章", "问答", "动态"],
      tags: ["前端", "Java", "Vue", "后端", "测试", "设计模式"],
      hotTopics: ["微服务", "分布式", "性能优化", "简历提升", "高并发"],
      articles: [],
      currentPage: 1,
      pageSize: 4,
      total: 0,
      loading: false,
      noMore: false,
      recommendedAuthors: [
        {name: "程序员小刚", desc: "Java 架构师 | 技术布道者"},
        {name: "前端大聪明", desc: "Vue & React 专栏作者"},
        {name: "测试女侠", desc: "自动化测试工程师"}
      ]
    };
  },
  mounted() {
    this.fetchArticles();
  },
  methods: {
    async fetchArticles() {
      if (this.loading || this.noMore) return;
      this.loading = true;
      try {
        let res = await ArticleApi.getAllArticle(this.currentPage, this.pageSize, {});
        res = res.data;
        if (res.code === 20000) {
          const list = res.data.records || [];
          if (list.length === 0) {
            this.noMore = true;
          } else {
            this.total = res.data.total || 0;
            const newArticles = list.map(item => ({
              articleId: item.articleId,
              title: item.title,
              // 增强版HTML标签去除，处理<style>等复杂标签
              content: this.stripHtml(item.content).slice(0, 100) + "...",
              views: item.viewCount,
              comments: item.commentCount,
              likes: item.likeCount,
              author: item.userName,
              time: this.formatTime(item.gmtCreate),
              cover: item.cover || "https://via.placeholder.com/300x180?text=No+Image"
            }));
            this.articles.push(...newArticles);
            this.currentPage++;
          }
        }
      } catch (error) {
        console.error("获取文章失败：", error);
      } finally {
        this.loading = false;
      }
    },
    // 增强版HTML标签去除方法，彻底处理所有标签和特殊内容
    stripHtml(html) {
      if (!html) return '';

      // 1. 先移除<style>和<script>标签及其内容（避免匹配错误）
      html = html.replace(/<style[^>]*>[\s\S]*?<\/style>/gi, '');
      html = html.replace(/<script[^>]*>[\s\S]*?<\/script>/gi, '');

      // 2. 移除所有HTML标签（包括自闭合标签和带属性的标签）
      html = html.replace(/<[^>]+>/g, '');

      // 3. 处理HTML实体
      html = html.replace(/&nbsp;/g, ' ');
      html = html.replace(/&lt;/g, '<');
      html = html.replace(/&gt;/g, '>');
      html = html.replace(/&amp;/g, '&');
      html = html.replace(/&quot;/g, '"');
      html = html.replace(/&apos;/g, "'");

      // 4. 处理连续空白（多个空格、换行合并为一个）
      html = html.replace(/\s+/g, ' ').trim();

      // 5. 处理可能残留的特殊符号
      html = html.replace(/[`~!@#$%^&*()_|+\-=?;:'",.<>\{\}\[\]\\\/]/g, '');

      return html;
    },
    formatTime(dateString) {
      const postTime = new Date(dateString);
      const now = new Date();
      const diffMs = now - postTime;
      const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24));
      if (diffDays === 0) return "今天";
      if (diffDays === 1) return "昨天";
      return `${diffDays}天前`;
    },
    goWriteArticle() {
      this.$router.push("/community/article/write");
    },
    goDetail(id) {
      if (!id) return;
      this.$router.push(`/community/article/${id}`);
    }
  }
};
</script>

<style scoped>
.community-container {
  max-width: 1400px;
  margin: 30px auto;
  padding: 0 20px;
  position: relative;
  margin-right: 200px;
}

/* 顶部导航栏容器，包含标签和按钮 */
.category-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
  padding: 0 8px;
  border-bottom: 1px solid #e4e7ed;
}

/* tabs区域 */
.tabs span {
  cursor: pointer;
  margin-right: 20px;
  padding: 6px 12px;
  font-size: 16px;
  font-weight: 500;
  border-radius: 6px;
  transition: background-color 0.3s ease;
  color: #606266;
}

.tabs span.active {
  background-color: #409eff;
  color: #fff;
}

/* 写文章按钮 */
.write-article-btn {
  background-color: #409eff;
  color: white;
  border: none;
  padding: 0 28px;
  height: 40px;
  border-radius: 24px;
  font-weight: 700;
  font-size: 16px;
  cursor: pointer;
  user-select: none;
  transition: background-color 0.3s ease;
}

.write-article-btn:hover {
  background-color: #66b1ff;
}

.main-layout {
  display: flex;
  gap: 40px;
  align-items: flex-start;
}

.tag-bar {
  margin: 10px 0 20px;
}

.tag {
  background-color: #f2f3f5;
  color: #555;
  padding: 6px 10px;
  margin-right: 10px;
  border-radius: 4px;
  font-size: 13px;
  cursor: pointer;
}

.article-item {
  padding: 22px 18px;
  border-radius: 8px;
  border: 1px solid #f1f1f1;
  transition: 0.3s ease;
  margin-bottom: 30px;
  background: #fff;
  cursor: pointer;
}

.article-content-area {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  gap: 20px;
}

.article-left {
  flex: 1;
}

.article-title {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 25px;
  margin-top: 30px;
  color: #333;
}

.article-title:hover {
  color: #66b1ff;
}

.author:hover {
  color: #66b1ff;
}

.article-content {
  font-size: 14px;
  color: #666;
  line-height: 1.6;
  margin-bottom: 10px;
}

.article-meta {
  display: flex;
  gap: 18px;
  font-size: 13px;
  color: #999;
  margin-top: 25px;
}

.article-cover {
  width: 220px;
  flex-shrink: 0;
  border-radius: 6px;
  overflow: hidden;
  text-align: center;
  margin-top: 10px;
}

.article-cover img {
  width: 100%;
  height: 130px;
  object-fit: cover;
  border-radius: 6px;
}

.cover-meta {
  margin-top: 6px;
  font-size: 13px;
  color: #999;
}

.card {
  background: #fff;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 24px;
  box-shadow: 0 0 8px rgba(0, 0, 0, 0.03);
}

.card-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 10px;
}

.author-list li {
  margin-bottom: 10px;
}

.author-name {
  font-weight: 500;
  color: #333;
}

.author-desc {
  font-size: 13px;
  color: #999;
}

.hot-topics .tag {
  display: inline-block;
  margin: 6px 8px 0 0;
}

.ad-img {
  width: 100%;
  height: auto;
  border-radius: 4px;
}

/* 加载更多文字样式 */
.load-more-container {
  text-align: center;
  margin: 20px 0;
}

.load-more-text {
  color: #409eff;
  font-weight: 500;
  cursor: pointer;
  font-size: 16px;
  user-select: none;
  transition: color 0.3s, text-decoration 0.3s;
}

.load-more-text:hover {
  text-decoration: underline;
  color: #66b1ff;
}

.loading-text,
.no-more-text {
  color: #999;
  font-size: 14px;
  user-select: none;
}
</style>
